package com.muyan.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5 {
    private static final String MD5 = "MD5";

    public static String convert(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance(MD5);
            md.update(plainText.getBytes());
            return byteToHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String convert(String plainText, int off, int len) {
        try {
            MessageDigest md = MessageDigest.getInstance(MD5);
            byte b[] = plainText.getBytes();
            md.update(b, off, len);
            return byteToHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String byteToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String s;
        for (byte b : bytes) {
            s = Integer.toHexString(b & 0XFF);
            if (s.length() == 1) {
                sb.append("0");
            }
            sb.append(s);
        }
        return sb.toString();
    }
}
